package com.bingkaimedia.dompetobeta.app;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.bingkaimedia.dompetobeta.R;
import com.bingkaimedia.dompetobeta.libs.AlertDialogManager;
import com.bingkaimedia.dompetobeta.libs.JSONfunctions;
import com.bingkaimedia.dompetobeta.libs.LazyAdapter2;
import com.bingkaimedia.dompetobeta.libs.SessionManager;
import com.bingkaimedia.dompetobeta.libs_image.ImageLoader;
import com.bingkaimedia.dompetobeta.libs_slidemenu.BaseActivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
 
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

@SuppressLint("NewApi")
public class Countries  extends BaseActivity implements OnClickListener {
	
	int current_page = 0;
	
	
	
	// XML node keys 
	//static final String KEY_SONG = "song"; // parent node
	public static final String KEY_VOUCHER_ID = "voucher_id";
	public static final String KEY_VOUCHER_NAME = "voucher_name"; 
	public static final String KEY_VOUCHER_TOTAL = "voucher_total";
	public static final String KEY_VOUCHER_TERSEDIA = "voucher_tersedia";
	public static final String KEY_VOUCHER_DETAIL = "voucher_detail";
	public static final String KEY_VOUCHER_DATE = "voucher_date";
	public static final String KEY_VOUCHER_DESCRIPTION = "voucher_description";
	public static final String KEY_MERCHANT_ID = "merchant_id";
	public static final String KEY_MERCHANT_NAME = "merchant_name";
	public static final String KEY_MERCHANT_CATEGORY = "merchant_category";
	public static final String KEY_MERCHANT_PHOTO = "merchant_photo";
	public static final String KEY_TRANSACTION_ID = "transaction_id";
	public static final String KEY_TRANSACTION_DATE = "transaction_date";
	public static final String KEY_TRANSACTION_IMAGE = "transaction_image";
	public static final String KEY_TRANSACTION_STATUS = "transaction_status";
	
	public static final String KEY_MY_CHANNEL_ID = "my_channel_id";
	public static final String KEY_CHANNEL_ID = "channel_id";
	public static final String KEY_USERS_ID = "users_id";
	public static final String KEY_CHANNEL_NAME = "channel_name";
	public static final String KEY_CHANNEL_ADDRESS = "channel_address";
	public static final String KEY_CHANNEL_PHOTO = "channel_photo";
	public static final String KEY_CHANNEL_NOTE = "channel_note";
	
	
	public static final String KEY_COUNTRIES_ID = "id_countries";  
	public static final String KEY_COUNTRIES_CODE = "countryCode";  
	public static final String KEY_COUNTRIES_NAME = "countryName";  
	public static final String KEY_COUNTRIES_PHONE = "countryPhone";  
	

	
	private String xml_countries_id;
	private String xml_countries_code;
	private String xml_countries_name;
	private String xml_countries_phone;
	 
	
	private String xml_voucher_id;
	private String xml_voucher_name;
	private String xml_voucher_total;
	private String xml_voucher_tersedia;
	private String xml_voucher_description;
	private String xml_voucher_detail;
	private String xml_voucher_date;
	private String xml_merchant_id;
	private String xml_merchant_name;
	private String xml_merchant_category;
	private String xml_merchant_photo;
	private String xml_transaction_id;
	private String xml_transaction_date;
	private String xml_transaction_image;
	private String xml_transaction_status;
	
	AlertDialogManager alert = new AlertDialogManager();
	
	private String xml_my_channel_id;
	private String xml_channel_id;
	private String xml_users_id;
	private String xml_channel_name;
	private String xml_channel_photo;
	private String xml_channel_note;
	private String xml_channel_address;

	private static String session_userid;
	private static String session_username;
	private static String session_password;
	private static String session_email;
	private static String session_country;
	private static String session_country_name;
	private static String session_city;
	private static String session_city_name;
	private static String session_checked;
	private static String session_channel;
	private static String session_category;
	private static String session_category_name;
    
    
    
    public ImageLoader imageLoader; 
    
    private String idtransaksi;
	String phonecode ="";
	String phonecode_nama ="";
 // Session Manager Class
 	SessionManager session;
 	
 	LazyAdapter2 adapter;
 	ArrayList<HashMap<String, String>> menuItems;
 	ProgressDialog pDialog;
 	HashMap<String, String> map = new HashMap<String, String>();
 	
 	ArrayList<HashMap<String, String>> diskonba_list = new ArrayList<HashMap<String, String>>();
 	
 	//ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
 	
 	//slide menu
 	private LinearLayout slidingPanel;
 	private boolean isExpanded;
 	private DisplayMetrics metrics;
 	private RelativeLayout headerPanel;
 	private int panelWidth;
 	private int panelWidth1;

 	private String sta="";
 	private String id_;
 	ArrayList nameValuePairs;
	String result = null;
	InputStream is = null;
	StringBuilder sb=null;
	ImageLoader imgLoader;
	String tanggal1,tanggal2;
 	private ImageView menuViewButton,menuRightButton;
 	
 	FrameLayout.LayoutParams menuPanelParameters;
 	FrameLayout.LayoutParams slidingPanelParameters;
 	LinearLayout.LayoutParams headerPanelParameters;
 	LinearLayout.LayoutParams listViewParameters;
 	

 	private CharSequence[] value={"Bandung", "Jakarta"};
	
 	private EditText txt_city;
 	private TextView txt_users_username;
	private Button send;
	private Button cancel;

 	private Spinner spinnerFood;

	private int count;
	private String json; 
	private JSONObject jsonobject;
	public String code;
	public String msg;
	
	private ArrayList<Countries_Array> countrieslist;
	final List<String> list = new ArrayList<String>();
	private SlidingMenu sm;
	 
	public Countries() {
		super(R.string.baru); 
	}


	@Override
	public void onBackPressed() { 
		Countries.this.finish();
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.countries);
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
		
        
        fungsi_menu(); 
     		

        txt_users_username=(TextView)findViewById(R.id.txt_users_username);    
		send=(Button)findViewById(R.id.send);    
		send.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				new Check().execute();
				

			    //System.out.println(session_userid);
			    //System.out.println(session_username);
			    //System.out.println(session_password);
			    //System.out.println(session_email);
			    //System.out.println(session_city);
			    //System.out.println("cek "+session_checked);
			}
		});
 	 

		nameValuePairs = new ArrayList();
		
		imgLoader = new ImageLoader(getApplicationContext());
		
		session = new SessionManager(getApplicationContext());
	    
	    HashMap<String, String> user = session.getUserDetails();
	     
	    // name
	    session_userid = user.get(SessionManager.id_users);
	    session_username = user.get(SessionManager.username);
	    session_password = user.get(SessionManager.password);
	    session_email = user.get(SessionManager.email);
	    session_country = user.get(SessionManager.country);
	    session_country_name = user.get(SessionManager.country_name);
	    session_city = user.get(SessionManager.city);
	    session_city_name = user.get(SessionManager.city_name);
	    session_checked = user.get(SessionManager.checked);
	    session_channel = user.get(SessionManager.channel);
	    session_category = "";
	    session_category_name = "";
		
	    txt_users_username.setText(session_country_name);
	 // getting intent data
        Intent in = getIntent();
         
        // Get XML values from previous intent
        id_ = in.getStringExtra(KEY_CHANNEL_ID); 
         
    		
        spinnerFood = (Spinner) findViewById(R.id.spinFood);
        //spinnerFood.setOnItemSelectedListener(this);
        countrieslist = new ArrayList<Countries_Array>();

        
        new GetCategories().execute();
       
        spinnerFood.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				//Toast.makeText(getBaseContext(), list.get(arg2).toString(),Toast.LENGTH_SHORT).show();
				 
				
				//System.out.println("print array list");
				String selec = spinnerFood.getSelectedItem().toString();
		
				Boolean exist = false;
				for(int i = 0; i < countrieslist.size(); i++) 
				{
					
					String select_array = countrieslist.get(i).getcountryName().toString();
					if(select_array.equalsIgnoreCase(selec)){
						//System.out.println((countrieslist.get(i).getcountryName()).toString());
						//System.out.println((countrieslist.get(i).getidcountries()).toString());
						
						phonecode = countrieslist.get(i).getidcountries().toString();
						phonecode_nama = countrieslist.get(i).getcountryName().toString();
						exist=true;
			            break;
        			}
					
				} 
				
				 
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		}); 
         
    }
	
	
	public void fungsi_menu(){
		
		setSlidingActionBarEnabled(true);
		 
        sm = getSlidingMenu();
		 
		LinearLayout header_vertical_divider_1 = (LinearLayout) findViewById(R.id.header_vertical_divider_1);
		LinearLayout header_vertical_divider_2 = (LinearLayout) findViewById(R.id.header_vertical_divider_2);
		ImageView diskonion_iconmenu = (ImageView) findViewById(R.id.diskonion_iconmenu);
		ImageView diskonion_iconhome = (ImageView) findViewById(R.id.diskonion_iconhome);
		ImageView diskonion_iconsearch = (ImageView) findViewById(R.id.diskonion_iconsearch);
		ImageView diskonion_iconcategory = (ImageView) findViewById(R.id.diskonion_iconcategory);
		
		
		
		diskonion_iconmenu.setOnClickListener(new OnClickListener() { 
	 			public void onClick(View v)  {
				sm.showMenu(); 
			}
		}); 
		
		diskonion_iconhome.setOnClickListener(new OnClickListener() { 
	 			public void onClick(View v)  {
				//sm.showSecondaryMenu();
 				Intent intent=new Intent(getApplicationContext(),Home.class);
 				startActivity(intent);
			}
		});
		
		diskonion_iconsearch.setOnClickListener(new OnClickListener() { 
	 			public void onClick(View v)  {
				//sm.showSecondaryMenu();
 				Intent intent=new Intent(getApplicationContext(),Search.class);
 				startActivity(intent);
			}
		});
		
		diskonion_iconcategory.setOnClickListener(new OnClickListener() { 
	 			public void onClick(View v)  {
				sm.showSecondaryMenu(); 
			}
		});
 		
	}
	
	 
	 
	private class GetCategories extends AsyncTask<Void, Void, Void> {

		 

		protected void onPreExecute() {
			
			super.onPreExecute();
			pDialog = new ProgressDialog(Countries.this);
			pDialog.setMessage("Getting data...");
			pDialog.setCancelable(true);
			pDialog.show();
			 
		}
		
		
		protected Void doInBackground(Void... params) {
			
			Global.URL = Global.link_countries;
			//System.out.println(Global.URL);  
			Global.URL = Global.URL.replace(" ", "%20");
			
			code="99";
			msg="Not connected to server";
			//System.out.println("Mulai do in background");
 
			try{ 
				json=JSONfunctions.getStringContent(Global.URL);
				jsonobject=new JSONObject(json); 
				code=jsonobject.getString("code");
				msg=jsonobject.getString("msg");
				 
			}
			catch (Exception e) 
			{
				e.printStackTrace();
				System.out.println("catch code msg");
				System.out.println(e);
				//pDialog.dismiss();
				//Toast.makeText(getApplicationContext(), "Something wrong in your connection", Toast.LENGTH_LONG).show();
			
			}
			
			System.out.println("code "+code);
			if(code.equalsIgnoreCase("99")){
				try{ 
					System.out.println(Global.URL);
					//json=JSONfunctions.getStringContent2(Global.URL);
					System.out.println(json); 
					 
				}
				catch (Exception e) 
				{
					e.printStackTrace();
					System.out.println("catch 1");
					System.out.println(e);

					//pDialog.dismiss();
					//Toast.makeText(getApplicationContext(), "Something wrong in your connection (1)", Toast.LENGTH_LONG).show();
				
				}
			}
			
			return null;   
		}
		
		@Override
		protected void onPostExecute(Void unused) {
			
			//System.out.println("onpostexecute"); 
			count = 0;  
			result = json;
 
			try{
				
		      	JSONArray jArray = new JSONArray(result);
		      	JSONObject json_data=null; 
		      	//System.out.println("array length");
		      	//System.out.println(jArray.length());
		      	
		      	for(int i=0;i<jArray.length();i++){
					json_data = jArray.getJSONObject(i);  
					xml_countries_id = json_data.getString(KEY_COUNTRIES_ID);  
					xml_countries_code = json_data.getString(KEY_COUNTRIES_CODE);  
					xml_countries_name = json_data.getString(KEY_COUNTRIES_NAME);  
					xml_countries_phone = json_data.getString(KEY_COUNTRIES_PHONE);  
					//System.out.println(xml_countries_id);  
					//System.out.println(xml_countries_code);  
					//System.out.println(xml_countries_name);  
					//System.out.println(xml_countries_phone);  
					//adapter.add(new SampleItem2(xml_countries_id, xml_countries_code, xml_countries_name));
					
					Countries_Array cat = new Countries_Array(xml_countries_id, xml_countries_code, xml_countries_name, xml_countries_phone);
					countrieslist.add(cat); 
					
					list.add(xml_countries_name); 
					Collections.sort(list); 
		      	} 
		      	
			}catch(JSONException e1){ 
				System.out.println("catch 2");
				System.out.println(e1);
				Toast.makeText(getBaseContext(), "Something wrong in your connection (2)", Toast.LENGTH_LONG).show();
			}catch (ParseException e1){ 
				System.out.println("catch 3");
				System.out.println(e1);
				Toast.makeText(getBaseContext(), "Something wrong in your connection (3)", Toast.LENGTH_LONG).show();	
			} 
			 
			if (pDialog.isShowing())
				pDialog.dismiss();
			populateSpinner();
			 
		}


		 
	}
	
	private void populateSpinner() {
		List<String> lables = new ArrayList<String>();
		List<String> lables2 = new ArrayList<String>();
		
		 

		for (int i = 0; i < countrieslist.size(); i++) {
			lables.add(countrieslist.get(i).getcountryName());
		}

		 
		
		// Creating adapter for spinner
		ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, lables);
		
		 
		// Drop down layout style - list view with radio button
		spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		 
		// attaching data adapter to spinner
		spinnerFood.setAdapter(spinnerAdapter); 
	}
	
	@SuppressLint("NewApi")
	class Check extends AsyncTask {

		private String json;
		private JSONObject jsonobject;
		private String code;
		private String msg;
		public String url2;

		@Override
		protected void onPreExecute() {
			
			super.onPreExecute();
			pDialog = new ProgressDialog(Countries.this);
			pDialog.setMessage("Please wait...");
			pDialog.setCancelable(true);
			pDialog.show();
			
			 url2 = Global.link_change_country +
					session_userid+"&"+ 
					"city="+phonecode;
			
			 
			url2 = url2.replace("+", "%20");
			url2 = url2.replace(" ", "%20"); 
			System.out.println(url2);
			
			SessionManager session;
	        session = new SessionManager(getApplicationContext());
	        HashMap<String, String> user = session.getUserDetails(); 
	        
	        session_userid = user.get(SessionManager.id_users);
		    session_username = user.get(SessionManager.username);
		    session_password = user.get(SessionManager.password);
		    session_email = user.get(SessionManager.email);
		    session_country = user.get(SessionManager.country);
		    session_country_name = user.get(SessionManager.country_name);
		    session_city = user.get(SessionManager.city);
		    session_city_name = user.get(SessionManager.city_name);
		    session_checked = user.get(SessionManager.checked);
		    session_channel = user.get(SessionManager.channel);
		    session_category = "";
		    session_category_name = "";

		}

		@Override
		protected Object doInBackground(Object... params) {

			try {
				json = JSONfunctions.getStringContent(url2);
				jsonobject = new JSONObject(json);
				code = jsonobject.getString("code");
				//code = "1";
				msg = jsonobject.getString("msg");
				//Toast.makeText(getApplicationContext(), "Mohon Tunggu",
				//		30000).show();
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Object result) {
			super.onPostExecute(result);
			
			if (pDialog.isShowing())
				pDialog.dismiss(); 
			
			if (code.equalsIgnoreCase("1")) { 
 
	            session.createLoginSession(session_userid, session_username, session_password, session_email, phonecode, phonecode_nama, session_city, session_city_name, session_checked, session_channel, session_category,session_category_name);
				
				 
				AlertDialog.Builder alertDialog = new AlertDialog.Builder(Countries.this); 
	            alertDialog.setTitle("Information"); 
	            alertDialog.setMessage("Country Changed."); 
	            alertDialog.setIcon(R.drawable.image_success); 
	            alertDialog.setPositiveButton("OK",
	                    new DialogInterface.OnClickListener() {
	                        public void onClick(DialogInterface dialog,int which) {
	                            // Write your code here to execute after dialog
	                        	Intent i = new Intent(getApplicationContext(), Countries.class);
	                            startActivity(i); 
	                            finish();
	                        }
	                    });
	            

	            // Showing Alert Message
	            alertDialog.show();
	            
				
			} else {
				alert.showAlertDialog(Countries.this, "Information", msg, false);
			}
		}

	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		
	}
	
	
	
}
